<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="50%" class="product-form-dialog">
    <div class="dialog-content">
      <!-- 头部区域 -->
      <div class="dialog-header">
        <div class="header-icon">
          <Icon icon="ep:goods" />
        </div>
        <div class="header-content">
          <h3 class="dialog-title">{{ dialogTitle }}</h3>
          <p class="dialog-subtitle">配置产品基本信息</p>
        </div>
      </div>

      <!-- 表单区域 -->
      <div class="form-container">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          v-loading="formLoading"
          class="enhanced-form"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-header">
              <Icon icon="ep:goods" class="section-icon" />
              <span class="section-title">基本信息</span>
            </div>

            <div class="form-grid">
              <el-form-item label="产品名称" prop="name" class="form-item">
                <div class="input-wrapper">
                  <Icon icon="ep:goods" class="input-icon" />
                  <el-input
                    v-model="formData.name"
                    placeholder="请输入产品名称"
                    class="enhanced-input"
                  />
                </div>
              </el-form-item>

              <el-form-item label="负责人" prop="ownerUserId" class="form-item">
                <div class="select-wrapper">
                  <Icon icon="ep:user" class="select-icon" />
                  <el-select
                    filterable
                    v-model="formData.ownerUserId"
                    placeholder="请选择负责人"
                    :disabled="formData.id"
                    class="enhanced-select"
                  >
                    <el-option
                      v-for="user in userList"
                      :key="user.id"
                      :label="user.nickname"
                      :value="user.id"
                    />
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="产品类型" prop="categoryId" class="form-item">
                <div class="tree-select-wrapper">
                  <Icon icon="ep:menu" class="tree-select-icon" />
                  <el-tree-select
                    v-model="formData.categoryId"
                    :data="productCategoryList"
                    :props="defaultProps"
                    check-strictly
                    node-key="id"
                    class="enhanced-tree-select"
                    placeholder="请选择产品类型"
                  />
                </div>
              </el-form-item>

              <el-form-item label="产品单位" prop="unit" class="form-item">
                <div class="select-wrapper">
                  <Icon icon="ep:scale-to-original" class="select-icon" />
                  <el-select
                    v-model="formData.unit"
                    class="enhanced-select"
                    placeholder="请选择单位"
                  >
                    <el-option
                      v-for="dict in getIntDictOptions(DICT_TYPE.CRM_PRODUCT_UNIT)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="产品编码" prop="no" class="form-item">
                <div class="input-wrapper">
                  <Icon icon="ep:document-copy" class="input-icon" />
                  <el-input
                    v-model="formData.no"
                    placeholder="请输入产品编码"
                    class="enhanced-input"
                  />
                </div>
              </el-form-item>

              <el-form-item label="价格" prop="price" class="form-item">
                <div class="price-wrapper">
                  <Icon icon="ep:money" class="price-icon" />
                  <el-input-number
                    v-model="formData.price"
                    placeholder="请输入价格"
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    class="enhanced-number"
                  />
                  <span class="price-unit">元</span>
                </div>
              </el-form-item>

              <el-form-item label="产品描述" prop="description" class="form-item">
                <div class="input-wrapper">
                  <Icon icon="ep:document" class="input-icon" />
                  <el-input
                    v-model="formData.description"
                    placeholder="请输入产品描述"
                    class="enhanced-input"
                  />
                </div>
              </el-form-item>

              <el-form-item label="上架状态" prop="status" class="form-item">
                <div class="select-wrapper">
                  <Icon icon="ep:switch" class="select-icon" />
                  <el-select
                    v-model="formData.status"
                    placeholder="请选择状态"
                    class="enhanced-select"
                  >
                    <el-option
                      v-for="dict in getIntDictOptions(DICT_TYPE.CRM_PRODUCT_STATUS)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel-btn">
          <Icon icon="ep:close" class="btn-icon" />
          取消
        </el-button>
        <el-button @click="submitForm" type="primary" :disabled="formLoading" class="confirm-btn">
          <Icon icon="ep:check" class="btn-icon" />
          确定
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as ProductApi from '@/api/crm/product'
import * as ProductCategoryApi from '@/api/crm/product/category'
import { defaultProps, handleTree } from '@/utils/tree'
import { getSimpleUserList, UserVO } from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'

defineOptions({ name: 'CrmProductForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const userId = useUserStore().getUser.id // 当前登录的编号
const formData = ref({
  id: undefined,
  name: undefined,
  no: undefined,
  unit: undefined,
  price: Number(undefined),
  status: undefined,
  categoryId: undefined,
  description: undefined,
  ownerUserId: -1
})
const formRules = reactive({
  name: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  no: [{ required: true, message: '产品编码不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
  categoryId: [{ required: true, message: '产品分类ID不能为空', trigger: 'blur' }],
  ownerUserId: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '价格不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductApi.getProduct(id)
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value.ownerUserId = userId
  }
  productCategoryList.value = handleTree(await ProductCategoryApi.getProductCategoryList({}))
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProductApi.ProductVO
    if (formType.value === 'create') {
      await ProductApi.createProduct(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductApi.updateProduct(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    no: undefined,
    unit: undefined,
    price: Number(undefined),
    status: undefined,
    categoryId: undefined,
    description: undefined,
    ownerUserId: -1
  }
  formRef.value?.resetFields()
}

/** 初始化 */
const productCategoryList = ref<Tree[]>([]) // 树形结构
const userList = ref<UserVO[]>([]) // 系统用户
onMounted(async () => {
  // 系统用户列表
  userList.value = await getSimpleUserList()
})
</script>

<style lang="scss" scoped>
.product-form-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;

    @media (max-width: 768px) {
      width: 95% !important;
      margin: 20px auto;
      max-height: 90vh;
    }
  }

  :deep(.el-dialog__header) {
    display: none;
  }

  :deep(.el-dialog__body) {
    padding: 0;
    max-height: 80vh;
    overflow-y: auto;
  }

  :deep(.el-dialog__footer) {
    padding: 0;
    border-top: 1px solid #e5e7eb;
  }
}

.dialog-content {
  background: #f8fafc;
}

/* 对话框头部 */
.dialog-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  color: white;
  border-radius: 10px;

  @media (max-width: 768px) {
    padding: 16px;
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
}

.header-icon {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;

  @media (max-width: 768px) {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
}

.header-content {
  flex: 1;
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;

  @media (max-width: 768px) {
    font-size: 16px;
  }
}

.dialog-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

/* 表单容器 */
.form-container {
  background: white;
  padding: 24px;

  @media (max-width: 768px) {
    padding: 16px;
  }
}

.enhanced-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #374151;
    font-size: 14px;

    @media (max-width: 768px) {
      font-size: 13px;
    }
  }
}

/* 表单区域 */
.form-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e5e7eb;

  @media (max-width: 768px) {
    margin-bottom: 16px;
    padding: 16px;
  }
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #0052cc;
}

.section-icon {
  color: #0052cc;
  font-size: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

/* 表单网格 */
.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

.form-item {
  margin-bottom: 0;
}

/* 输入框样式 */
.input-wrapper,
.select-wrapper,
.tree-select-wrapper,
.price-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
}

.input-icon,
.select-icon,
.tree-select-icon,
.price-icon {
  position: absolute;
  left: 12px;
  color: #6b7280;
  font-size: 16px;
  z-index: 1;
}

.enhanced-input,
.enhanced-select,
.enhanced-tree-select,
.enhanced-number {
  width: 100%;

  :deep(.el-input__wrapper) {
    padding-left: 40px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;
    min-height: 40px;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }

  :deep(.el-input__inner) {
    font-size: 14px;

    @media (max-width: 768px) {
      font-size: 16px; // 防止iOS缩放
    }
  }

  :deep(.el-input__suffix) {
    right: 12px;
  }
}

/* 树形选择器样式 */
.enhanced-tree-select {
  :deep(.el-tree-select__wrapper) {
    padding-left: 40px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;
    min-height: 40px;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }

  :deep(.el-tree-select__tags) {
    padding-left: 40px;
  }

  :deep(.el-tree-select__placeholder) {
    padding-left: 40px;
    font-size: 14px;
    color: #a1a1aa;

    @media (max-width: 768px) {
      font-size: 16px;
    }
  }

  :deep(.el-tree-select__suffix) {
    right: 12px;
  }
}

/* 价格输入框 */
.price-wrapper {
  .price-unit {
    position: absolute;
    right: 12px;
    color: #6b7280;
    font-size: 14px;
    font-weight: 500;
    z-index: 1;
  }

  .enhanced-number {
    :deep(.el-input__wrapper) {
      padding-right: 40px;
      background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
      border: 2px solid #f59e0b;
    }

    :deep(.el-input__inner) {
      color: #92400e;
      font-weight: 600;
      font-size: 16px;
    }

    :deep(.el-input-number__increase),
    :deep(.el-input-number__decrease) {
      background: rgba(245, 158, 11, 0.1);
      border-color: #f59e0b;
      color: #92400e;

      &:hover {
        background: rgba(245, 158, 11, 0.2);
      }
    }
  }
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  background: white;

  @media (max-width: 768px) {
    padding: 16px;
    flex-direction: column;
    gap: 8px;
  }
}

.cancel-btn {
  border: 2px solid #e5e7eb;
  color: #6b7280;
  background: white;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.2s ease;
  min-height: 40px;

  &:hover {
    border-color: #d1d5db;
    color: #374151;
  }

  @media (max-width: 768px) {
    width: 100%;
    order: 2;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

.confirm-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  color: white;
  transition: all 0.2s ease;
  min-height: 40px;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  @media (max-width: 768px) {
    width: 100%;
    order: 1;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

:deep(.el-loading-spinner) {
  .circular {
    width: 32px;
    height: 32px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .dialog-content {
    background: #1f2937;
  }

  .form-container {
    background: #374151;
  }

  .form-section {
    background: #4b5563;
    border-color: #6b7280;
  }

  .section-title {
    color: #f9fafb;
  }

  .section-header {
    border-color: #60a5fa;
  }

  .section-icon {
    color: #60a5fa;
  }

  .enhanced-input,
  .enhanced-select,
  .enhanced-number {
    :deep(.el-input__wrapper) {
      background: #4b5563;
      border-color: #6b7280;

      .el-input__inner {
        color: #f9fafb;
      }
    }
  }

  .enhanced-tree-select {
    :deep(.el-tree-select__wrapper) {
      background: #4b5563;
      border-color: #6b7280;
    }

    :deep(.el-tree-select__placeholder) {
      color: #9ca3af;
    }
  }

  .input-icon,
  .select-icon,
  .tree-select-icon,
  .price-icon {
    color: #d1d5db;
  }

  .price-unit {
    color: #d1d5db;
  }

  .price-wrapper {
    .enhanced-number {
      :deep(.el-input__wrapper) {
        background: linear-gradient(135deg, #92400e 0%, #b45309 100%);
        border-color: #f59e0b;
      }

      :deep(.el-input__inner) {
        color: #fbbf24;
      }

      :deep(.el-input-number__increase),
      :deep(.el-input-number__decrease) {
        background: rgba(251, 191, 36, 0.1);
        border-color: #f59e0b;
        color: #fbbf24;

        &:hover {
          background: rgba(251, 191, 36, 0.2);
        }
      }
    }
  }

  .dialog-footer {
    background: #374151;
  }

  .enhanced-form {
    :deep(.el-form-item__label) {
      color: #f9fafb;
    }
  }

  :deep(.el-loading-mask) {
    background: rgba(55, 65, 81, 0.9);
  }
}

/* 高对比度模式适配 */
@media (prefers-contrast: high) {
  .enhanced-input,
  .enhanced-select,
  .enhanced-number {
    :deep(.el-input__wrapper) {
      border: 2px solid #0052cc;
      box-shadow: none;

      &:hover,
      &.is-focus {
        border-color: #1d4ed8;
        box-shadow: 0 0 0 2px rgba(0, 82, 204, 0.2);
      }
    }
  }

  .enhanced-tree-select {
    :deep(.el-tree-select__wrapper) {
      border: 2px solid #0052cc;
      box-shadow: none;

      &:hover,
      &.is-focus {
        border-color: #1d4ed8;
        box-shadow: 0 0 0 2px rgba(0, 82, 204, 0.2);
      }
    }
  }

  .cancel-btn {
    border: 2px solid #6b7280;
  }

  .confirm-btn {
    background: #0052cc;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }
}

/* 减少动画模式适配 */
@media (prefers-reduced-motion: reduce) {
  .enhanced-input,
  .enhanced-select,
  .enhanced-tree-select,
  .enhanced-number,
  .cancel-btn,
  .confirm-btn {
    transition: none;
  }

  .confirm-btn {
    &:hover {
      transform: none;
    }
  }
}

/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
  .enhanced-input,
  .enhanced-select,
  .enhanced-tree-select,
  .enhanced-number {
    :deep(.el-input__wrapper) {
      min-height: 44px;
    }
  }

  .enhanced-tree-select {
    :deep(.el-tree-select__wrapper) {
      min-height: 44px;
    }
  }

  .cancel-btn,
  .confirm-btn {
    min-height: 44px;
    padding: 12px 20px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 480px) {
  .dialog-header {
    padding: 12px;
  }

  .form-container {
    padding: 12px;
  }

  .form-section {
    padding: 12px;
    margin-bottom: 12px;
  }

  .dialog-footer {
    padding: 12px;
  }

  .form-grid {
    gap: 12px;
  }
}

/* 横屏模式适配 */
@media (max-width: 768px) and (orientation: landscape) {
  .dialog-header {
    padding: 12px 16px;
    flex-direction: row;
    text-align: left;
  }

  .form-container {
    padding: 16px;
  }

  .form-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }
}
</style>
